<div class="easyui-layout" data-options="fit:true">

<!--    查询 -->
    <div data-options="region:'north',border:false" style="height:80px;width: 1150px;padding:5px">
        <form id="accBookBorrow_query_form" style="height:80px;width: 1150px">
            书名： <input class="easyui-textbox" id="accBookBorrow_query_form_book_name" name="book_name" />
            类型： <input id="accBookBorrow_query_form_type_id" name="type_id" />
            学号： <input class="easyui-numberbox" id="accBookBorrow_query_form_student_id" name="student_id" data-options="min:1" />
            借书时间： <input class="easyui-datebox" data-options="editable:false,required:false,validType:'date'"
                         id="accBookBorrow_query_form_bdate_start" name="bdate_start" />
            至： <input class="easyui-datebox" data-options="editable:false,required:false,validType:'date'"
                      id="accBookBorrow_query_form_bdate_end" name="bdate_end" />

            <a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'icon-add'"
               style="width: 125px" onclick='accBookBorrowAdd();'>新增借阅</a>
            <br>
            作者： <input id="accBookBorrow_query_form_author_id" name="author_id" />
            状态： <input id="accBookBorrow_query_form_status" name="status" />
            学生： <input class="easyui-textbox" id="accBookBorrow_query_form_student_name" name="student_name" />
            还书时间： <input class="easyui-datebox" data-options="editable:false,required:false,validType:'date'"
                         id="accBookBorrow_query_form_rdate_start" name="rdate_start" />
            至： <input class="easyui-datebox" data-options="editable:false,required:false,validType:'date'"
                      id="accBookBorrow_query_form_rdate_end" name="rdate_end" />
            <a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'icon-search'" style="width: 61px;height: 30px;"
               onclick='accBookBorrowQuery();'>查询</a>
            <a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'icon-clear'" style="width: 61px;height: 30px;"
               onclick='accBookBorrowQueryClear();'>重置</a>
        </form>
    </div>

    <!--        借阅列表-->
    <div data-options="region:'center'" style="border:0;padding:5px;overflow:hidden;">
        <div style="width:1150px;height:100%;overflow:auto;border:1px solid #ccc;float:left">
            <table id="accBookBorrow_bookBorrow_grid"></table>
        </div>
    </div>
</div>

<!-- 新增借阅-->
<div id="accBookBorrow_add_dialog">
    <div class="easyui-layout" data-options="fit:true">
        <div data-options="region:'north',title:'',split:true" style="height:70px;">
            <form id="accBookBorrow_add_form" method="post">
                学生学号：<input class="easyui-numberbox" id="accBookBorrow_add_form_student_id" name="student_id" data-options="min:1" required />
                学生姓名：<input class="easyui-textbox" id="accBookBorrow_add_form_student_name" name="student_name" required/>
                <br>
                搜索图书：<input id="accBookBorrow_add_form_stock_id" name="stock_id" />
            </form>
        </div>
        <div data-options="region:'center',title:''" style="height:240px">
            <table id="accBookBorrow_add_grid"></table>
        </div>
        <div data-options="region:'south',title:'',split:true" style="height:40px;">
            <div style="float:left">
                合计：<input class="easyui-numberbox" id="accBookBorrow_add_num" style="width:50px;" data-options="min:0,value:0" readonly required /> 本
            </div>
            <div style="float:right">
                <a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'icon-save'" 
                   onclick="accBookBorrow_add_save()">保存</a>
                <a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'icon-clear'" 
                   onclick="accBookBorrow_add_close()">关闭</a>
            </div>
        </div>

    </div>
</div>

<script>

    $(function () {
        initBookBorrowComponents();
        initBookBorrowGrid();
    });
    
    function initBookBorrowComponents() {
        $("#accBookBorrow_query_form_type_id").combogrid({
            url: '/queryBookTypes',
            idField: 'id', textField: 'name',
            panelWidth: 160, panelHeight: 200,
            editable: true, mode: 'remote',
            columns: [
                [
                    {field: 'id', title: '编号', width: 50},
                    {field: 'name', title: '类型', width: 100}
                ]
            ],
            loadFilter: function (data) {
                if (data.data) return data.data;
                else return data;
            },
            onClickRow: function (value, row, index) {}
        });

        $("#accBookBorrow_query_form_author_id").combogrid({
            url: '/queryBookAuthors',
            idField: 'id', textField: 'name',
            panelWidth: 210, panelHeight: 200,
            editable: true, mode: 'remote',
            columns: [
                [
                    {field: 'id', title: '编号', width: 50},
                    {field: 'name', title: '姓名', width: 100},
                    {field: 'sex', title: '性别', width: 50,
                        formatter: function (value, row, index) {
                            if (value === 0) {
                                return '女';
                            } else if (value === 1) {
                                return '男';
                            } else {
                                return '';
                            }
                        }
                    }
                ]
            ],
            loadFilter: function (data) {
                if (data.data) return data.data;
                else return data;
            },
            onClickRow: function (value, row, index) {}
        });

        $("#accBookBorrow_query_form_status").combobox({
            valueField: 'id', textField: 'text',
            panelHeight: 99, editable: false,
            data: [
                {"id": 'X', "text": "全部", selected: true},
                {"id": 'Y', "text": "借阅"},
                {"id": 'N', "text": "已还"}
            ]
        });

        $("#accBookBorrow_add_grid").datagrid({
            data:[],
            striped : true, fit : true, singleSelect : true,
            columns : [
                [
                    {field:"stock_id", hidden:true},
                    {field:"book_name", title:"书名", width:150, align:"center", halign:"center"},
                    {field:"book_type_name", title:"类型", width:100, align:"center", halign:"center"},
                    {field:"book_author_name", title:"作者", width:100, align:"center", halign:"center"},
                    {field:"book_num", title:"数量", width:60, align:"center", halign:"center",
                        editor:{
                            type:"numberbox",
                            options:{min:1,precision:0}
                        }
                    },
                    {field:'ope', title:'操作', width:90, align:'center', halign:'center'}
                ]
            ],
            onDblClickRow:function(rowIndex, rowData){},
            onLoadSuccess:function(data){}
        });

        $("#accBookBorrow_add_form_stock_id").combogrid({
            url: '/queryAllBookStocks',
            idField: 'id', textField: 'book_name',
            panelWidth: 550, panelHeight: 350,
            editable: true, mode: 'remote',
            pagination: true, pageSize: 200, pageList : [200],
            columns: [
                [
                    {field: 'id', title: '编码', width: 50},
                    {field: 'book_name', title: '书名', width: 150},
                    {field: 'book_type_name', title: '类型', width: 100},
                    {field: 'book_author_name', title: '作者', width: 100},
                    {field: 'num', title: '库存', width: 50},
                    {field: 'x', title: '操作', width: 50,
                        formatter: function (value, row, index) {
                            var s = '';
                            if (row.num > 0) {
                                s = '<a href="javascript:void(0)" onclick="insertBookBorrowGrid(\'' + encodeURI(JSON.stringify(row)) + '\')">借阅</a>';
                            }

                            return s;
                        }
                    }
                ]
            ],
            loadFilter: function (data) {
                if (data.data) return data.data;
                else return data;
            },
            onClickRow: function (value, row, index) {}
        });
    }

    function initBookBorrowGrid() {
        $('#accBookBorrow_bookBorrow_grid').datagrid({
            url: '/queryAllBookBorrows',
            idField: 'id',
            // fitColumns: true,
            fit: true, scrollbarSize: 1, striped: true,
            checkOnSelect: false, selectOnCheck: false, singleSelect: true,
            pagination: true, pageSize: 15, pageList : [15, 30, 60 ],
            columns: [
                [
                    {field: 'id', title: '编码', width: 50, align: 'center', halign: 'center'},
                    {field: 'student_id', title: '学生编号', width: 100, align: 'center', halign: 'center'},
                    {field: 'student_name', title: '学生姓名', width: 100, align: 'center', halign: 'center'},
                    {field: 'book_name', title: '书名', width: 150, align: 'center', halign: 'center'},
                    {field: 'book_type_name', title: '类型', width: 100, align: 'center', halign: 'center'},
                    {field: 'book_author_name', title: '作者', width: 100, align: 'center', halign: 'center'},
                    {field: 'status', title: '状态', width: 50, align: 'center', halign: 'center',
                        formatter: function (value, row, index) {
                            if (value === 'Y') {
                                return '借阅';
                            } else if (value === 'N') {
                                return '已还';
                            } else {
                                return '';
                            }
                        }
                    },
                    {field: 'btime', title: '借书时间', width: 180, align: 'center', halign: 'center'},
                    {field: 'rtime', title: '还书时间', width: 180, align: 'center', halign: 'center',
                        formatter: function (value, row, index) {
                            if (row.status === 'Y') {
                                return '暂无'
                            } else {
                                return value;
                            }
                        }
                    },
                    {field: 'x', title: '操作', width: 70, align: 'center', halign: 'center',
                        formatter: function (value, row, index) {
                            var s = '';
                            if (row.status === 'Y') {
                                s = '<a href="javascript:void(0)" onclick="bookReturnButton(\'' + encodeURI(JSON.stringify(row)) + '\')">还书</a>';
                            }

                            return s;
                        }
                    }
                ]
            ],
            loadFilter: function (data) {
                if (data.data) return data.data;
                else return data;
            },
            onLoadSuccess: function (node, data) {},
            onClickRow: function (index, row) {}
        });
    }

    function accBookBorrowQuery() {
        $("#accBookBorrow_bookBorrow_grid").datagrid('load', {
            book_name:$('#accBookBorrow_query_form_book_name').val(),
            type_id:$('#accBookBorrow_query_form_type_id').val(),
            student_id:$('#accBookBorrow_query_form_student_id').val(),
            bdate_start:$('#accBookBorrow_query_form_bdate_start').val(),
            bdate_end:$('#accBookBorrow_query_form_bdate_end').val(),
            author_id:$('#accBookBorrow_query_form_author_id').val(),
            status:$('#accBookBorrow_query_form_status').val(),
            student_name:$('#accBookBorrow_query_form_student_name').val(),
            rdate_start:$('#accBookBorrow_query_form_rdate_start').val(),
            rdate_end:$('#accBookBorrow_query_form_rdate_end').val()
        });
    }
    
    function accBookBorrowQueryClear() {
        $('#accBookBorrow_query_form_book_name').textbox('clear');
        $('#accBookBorrow_query_form_type_id').combogrid('clear');
        $('#accBookBorrow_query_form_student_id').numberbox('clear');
        $('#accBookBorrow_query_form_bdate_start').datebox('clear');
        $('#accBookBorrow_query_form_bdate_end').datebox('clear');
        $('#accBookBorrow_query_form_author_id').combogrid('clear');
        $('#accBookBorrow_query_form_status').combobox('setValue', 'X');
        $('#accBookBorrow_query_form_student_name').textbox('clear');
        $('#accBookBorrow_query_form_rdate_start').datebox('clear');
        $('#accBookBorrow_query_form_rdate_end').datebox('clear');
        $("#accBookBorrow_bookBorrow_grid").datagrid('load', {
            book_name: null,
            type_id: null,
            student_id: null,
            bdate_start: null,
            bdate_end: null,
            author_id: null,
            status: null,
            student_name: null,
            rdate_start: null,
            rdate_end: null
        });
    }

    function bookReturnButton(data) {
        data = JSON.parse(decodeURI(data));

        var borrow_id = data.id;
        var stock_id = data.stock_id;

        $.messager.confirm('确认', '您确认想要归还该书吗？', function (r) {
            if (!r) {return;}

            $.ajax({
                url: '/bookReturn',
                type: "post",
                data: {id: borrow_id, stock_id: stock_id},
                dataType: "json",
                async: false,
                success: function (data) {
                    if (data.code !== 200) {
                        $.messager.alert("提示", data.message, 'info');
                        return;
                    }

                    $.messager.show({title: '提示', msg: '还书成功！', timeout: 2000, showType: 'slide'});
                    $("#accBookBorrow_bookBorrow_grid").datagrid("reload");
                }
            });
        });
    }
    
    function accBookBorrowAdd() {
        // 新加载库存 combogrid
        $("#accBookBorrow_add_form_stock_id").combogrid({});

        $("#accBookBorrow_add_dialog").dialog({
            title :'图书借阅', iconCls: 'icon-add',
            width: 700, height: 500, modal: true, shadow: true,
            onClose: function(){
                // 清除数据
                // 清除学号和姓名
                $("#accBookBorrow_add_form_student_id").numberbox('clear');
                $("#accBookBorrow_add_form_student_name").textbox('clear');

                // 清除图书数据
                $("#accBookBorrow_add_form_stock_id").combogrid('setValue', '');

                // 清除表格数据
                var rows = $("#accBookBorrow_add_grid").datagrid('getRows');
                var len = rows.length;
                for (var i = 0; i < len; i++) {
                    $("#accBookBorrow_add_grid").datagrid('deleteRow', 0);
                }

                // 清除总计数据
                $("#accBookBorrow_add_num").numberbox('setValue', 0);
            }
            // onOpen: function(){} 不能有这个方法，否则出现未知错误，比如插入数据不显示等
        });
    }

    function insertBookBorrowGrid(data) {
        data = JSON.parse(decodeURI(data));

        var rows = $("#accBookBorrow_add_grid").datagrid('getRows');

        // 判断要添加的 stock_id 是否已在列表中
        // 如果已存在，则不能再次添加
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (data.id === row.stock_id) {
                $.messager.alert("提示", data.book_name + "：已存在，不能再次添加！", 'info');
                return;
            }
        }

        var index = rows.length;

        // 插入
        $("#accBookBorrow_add_grid").datagrid('insertRow', {
            index: index,
            row: {
                stock_id: data.id,
                book_name: data.book_name,
                book_type_name: data.book_type_name,
                book_author_name: data.book_author_name,
                book_num: 1,
                ope: '<a href="javascript:void(0)" onclick="deleteBookBorrowGrid(' + data.id + ')">移除</a>'
            }
        });

        // 总计
        $("#accBookBorrow_add_num").numberbox('setValue',
            $("#accBookBorrow_add_grid").datagrid('getRows').length);
    }

    // 根据 stock_id 删除
    function deleteBookBorrowGrid(stock_id) {
        var rows = $("#accBookBorrow_add_grid").datagrid('getRows');

        // 查找，删除
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (row.stock_id === stock_id) {
                $("#accBookBorrow_add_grid").datagrid('deleteRow', i);

                // 总计
                $("#accBookBorrow_add_num").numberbox('setValue',
                    $("#accBookBorrow_add_grid").datagrid('getRows').length);
                return;
            }
        }
    }

    function accBookBorrow_add_save() {

        if (!$('#accBookBorrow_add_form').form('validate')) {
            $.messager.alert("提示", "请先添加学生信息再保存！", 'info');
            return;
        }

        var books = $("#accBookBorrow_add_grid").datagrid('getRows');
        if (books.length <= 0) {
            $.messager.alert("提示", "请先添加图书再保存！", 'info');
            return;
        }

        var student_id = $("#accBookBorrow_add_form_student_id").numberbox('getValue');
        var student_name = $("#accBookBorrow_add_form_student_name").textbox('getValue');

        // 组织请求数据 borrow_infos
        var borrow_infos = [];
        for (var i = 0; i < books.length; i++) {
            var tmp = {
                stock_id: books[i].stock_id,
                student_id: student_id,
                student_name: student_name
            };

            borrow_infos.push(tmp);
        }

        $.ajax({
            url: '/bookBorrowSave',
            type: "post", async: false,
            // 以下三者配套
            data: JSON.stringify(borrow_infos), dataType: "json", contentType: 'application/json',
            success: function (data) {
                if (data.code !== 200) {
                    $.messager.alert("提示", data.message, 'info');
                    return;
                }

                $.messager.show({title: '提示', msg: '图书借阅成功！', timeout: 2000, showType: 'slide'});

                $("#accBookBorrow_add_dialog").dialog("close");
                $("#accBookBorrow_bookBorrow_grid").datagrid("reload");
            }
        });

    }

    function accBookBorrow_add_close(){
        $("#accBookBorrow_add_dialog").dialog("close");
    }
    
</script>